package com.gz.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/calServlet")
public class CalServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String num1 = request.getParameter("num1");
        String num2 = request.getParameter("num2");

        int a= 0;
        boolean flag = false;
        try {
            a = Integer.parseInt(num1)+Integer.parseInt(num2);
            flag = true;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if(flag) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("<h1>num1+num2= "+a+"</h1>");
            writer.close();
        }else {
            response.sendRedirect("/tomcat/cal.html");
        }
    }
}
